<template>
  <map
    id="map"
    ref="mapRef"
    class="base-map"
    :style="mapStyle"
    :enable-traffic="enableTraffic"
    :scale="scale"
    :latitude="latitude"
    :longitude="longitude"
    :polyline="polyline"
    :polygons="polygon"
    :markers="processedMarkers"
    :include-points="includePoints"
    @markertap="markerTapHandler"
    @callouttap="callouttapTapHandler"
    @tap="closeClickHandler"
  >
    <template>
      <building-view
        :ref="'marker_view_' + item.id"
        v-for="item in buildingViewList"
        :key="item.id"
        :data="item"
      >
      </building-view>
      <poi-marker
        v-for="item in poiViewList"
        :key="item.id"
        :ref="'marker_view_' + item.id"
        :data="item"
      >
      </poi-marker>
      <icon-view
        v-for="item in matchingPoiViewList"
        :key="item.id"
        :ref="'marker_view_' + item.id"
        :data="item"
        @click="matchingPoiViewClickHandler"
      >
      </icon-view>
      <icon-view
        v-for="item in matchingViewList"
        :key="item.id"
        :ref="'marker_view_' + item.id"
        :data="item"
        @click="matchingPoiViewClickHandler"
      >
      </icon-view>
      <EmptyTooltip
        v-for="item in emptyList"
        :key="item.id"
        :ref="'marker_view_' + item.id"
        :data="item"
      >
      </EmptyTooltip>
      <matching-view
        v-for="item in selectMatchingViewList"
        :key="item.id"
        :ref="'marker_view_' + item.id"
        :data="item"
        @click="matchingViewImghandleClick"
      >
      </matching-view>
      <bim-image
        v-for="item in bimImageViewList"
        :key="item.id"
        :ref="'marker_view_' + item.id"
        :data="item"
      >
      </bim-image>
    </template>
  </map>
</template>

<script>
import BuildingView from './../building-view/index.vue'
import PoiMarker from './../poi-marker/index.vue'
import MatchingView from './../matching-view/index.vue'
import IconView from './../icon-view/index.vue'
import { createLabel } from './.././../utils/index'
import { getBoundsBox } from './../../utils/index'
import BimImage from './../bim-image/index.vue'
import EmptyTooltip from '../icon-view/empty-tooltip.vue'
let mapCtx = null
export default {
  name: 'MapView',
  components: {
    BuildingView,
    PoiMarker,
    MatchingView,
    IconView,
    BimImage,
    EmptyTooltip,
  },
  props: {
    latitude: {
      type: Number,
      default: 0,
    },
    longitude: {
      type: Number,
      default: 0,
    },
    // 实时路况
    enableTraffic: {
      type: Boolean,
      default: true,
    },
    scale: {
      type: Number,
      default: 13,
    },
    markers: {
      type: Array,
      default: () => [],
    },
    polyline: {
      type: Array,
      default: () => [],
    },
    polygon: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    markers: {
      handler(newVal) {
        this.processedMarkers = this.getAllMarkers()
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      map: null,
      selectedMarkerId: null,
      poiViewList: [],
      buildingViewList: [],
      processedMarkers: [],
      poiMarkers: [],
      emptyMarkers: [],
      emptyList: [],
      buildingMarkers: [],
      labelMarkers: [],
      matchingMarkers: [],
      matchingPoiMarkers: [],
      matchingPoiViewList: [],
      matchingViewList: [],
      selectMatchingViewList: [],
      selectMatchingMarkers: [],
      bimImageMarkers: [],
      bimImageViewList: [],
      markerId: 10000,
      includePoints: [],
    }
  },
  computed: {
    mapStyle() {
      return {
        height: `100vh`,
        width: '100%',
      }
    },
  },
  mounted() {
    this.processedMarkers = this.getAllMarkers()
    this.initAmapMap()
  },
  methods: {
    initAmapMap() {
      // mapCtx = wx.createMapContext('map', this)
    },
    /**
     * marker点击事件
     * @param {*} e
     */
    markerTapHandler1(e) {
      // 不改变气泡显示状态，让气泡始终显示
      this.$emit('markertap', e)
      console.log('点击了地图标记')
      const markerId = e.detail.markerId
      const datas = [...this.matchingMarkers, ...this.matchingPoiMarkers]
      if (this.selectedMarker) {
        this.processedMarkers = this.processedMarkers.filter(
          marker => marker.id !== this.selectedMarker.id
        )
        if (this.selectedMarker.id === markerId) {
          return
        }
        this.$nextTick(() => {
          if (this.selectedMarker.id !== markerId) {
            this.selectedMarker.callout.display = 'BYCLICK '
            this.processedMarkers.push(this.selectedMarker)
          }
        })
      }
      for (let i = 0; i < datas.length; i++) {
        const marker = datas[i]
        if (markerId === marker.id) {
          this.selectedMarker = marker
          this.processedMarkers = this.processedMarkers.filter(
            marker => marker.id !== this.selectedMarker.id
          )
          this.$nextTick(() => {
            this.selectedMarker.callout.display = 'ALWAYS '
            this.processedMarkers.push(this.selectedMarker)
          })
          return
        }
      }
    },
    markerTapHandler(e) {
      const markerId = e.detail.markerId

      // 如果之前有激活的标记点，则关闭它的气泡
      if (this.activeMarkerId !== null && this.activeMarkerId !== markerId) {
        this.closeCallout(this.activeMarkerId)
      }

      // 更新当前激活的标记点id
      this.activeMarkerId = markerId

      // 打开新标记点的气泡
      this.openCallout(markerId)
    },
    openCallout(markerId) {
      // 打开指定标记点的气泡
      const marker = this.markers.find(item => item.id === markerId)
      if (marker) {
        marker.callout.display = 'BYCLICK' // 设置为点击时显示
        this.$forceUpdate() // 强制更新视图
      }
    },
    closeCallout(markerId) {
      // 关闭指定标记点的气泡
      const marker = this.markers.find(item => item.id === markerId)
      if (marker) {
        marker.callout.display = 'NEVER' // 设置为不显示
        this.$forceUpdate() // 强制更新视图
      }
    },
    callouttapTapHandler(e) {
      // 不改变气泡显示状态，让气泡始终显示
      this.$emit('markertap', e)
      console.log('点击了地图气泡')
    },

    /**
     * 地图点击事件
     * @param {*} e
     */
    closeClickHandler(e) {
      // 移除关闭气泡的逻辑，让气泡始终显示
      this.selectMatchingMarkers = []
      this.processedMarkers = this.getAllMarkers()
      this.$emit('maptap', e)
    },
    // 创建泡泡标记点
    createMarker(data, anchorY) {
      let refs = this.$refs[`marker_view_${data.id}`]
      if (Array.isArray(refs) && refs.length) {
        refs = refs[0]
      }
      const html = refs ? refs.$el.innerHTML : ''
      return {
        data,
        latitude: data.latitude,
        longitude: data.longitude,
        id: this.markerId++,
        width: 1,
        height: 1,
        iconPath: '/industry/static/1.png',
        joinCluster: true,
        anchor: {
          x: 0,
          y: 0,
        },
        callout: {
          content: html,
          padding: 1,
          borderWidth: 0,
          borderColor: 'transparent',
          borderRadius: 0,
          bgColor: 'transparent',
          boxShadow: 'none',
          display: 'ALWAYS',
        },
      }
    },
    // 创建图片票房点
    createIconMarker(data) {
      let refs = this.$refs[`marker_view_${data.id}`]
      if (Array.isArray(refs) && refs.length) {
        refs = refs[0]
      }
      const html = refs ? refs.$el.innerHTML : ''
      return {
        data,
        latitude: data.latitude,
        longitude: data.longitude,
        id: data.id,
        width: 1,
        height: 1,
        iconPath: `/industry/static/map/poi_${data.iconType}.png`,
        joinCluster: true,
        anchor: {
          x: 0,
          y: 0,
        },
        callout: {
          content: html,
          padding: 1,
          borderWidth: 0,
          borderColor: 'transparent',
          borderRadius: 0,
          bgColor: 'transparent',
          boxShadow: 'none',
          display: 'ALWAYS',
        },
      }
    },
    createEmptyMarker(data) {
      if (!data.longitude || !data.latitude) return

      const id = this.markerId++

      this.emptyList.push({
        id,
        iconType: data.iconType,
      })

      this.$nextTick(() => {
        let refs = this.$refs[`marker_view_${id}`]
        if (Array.isArray(refs) && refs.length) {
          refs = refs[0]
        }

        const html = refs ? refs.$el.innerHTML : ''

        this.emptyMarkers.push({
          data,
          latitude: data.latitude,
          longitude: data.longitude,
          id,
          width: 1,
          height: 1,
          iconPath: `/industry/static/map/street_${data.iconType}_empty.png`,
          joinCluster: true,
          anchor: {
            x: 0,
            y: 0,
          },
          callout: {
            content: html,
            padding: 1,
            borderWidth: 0,
            borderColor: 'transparent',
            borderRadius: 0,
            bgColor: 'transparent',
            boxShadow: 'none',
            display: 'ALWAYS',
          },
        })

        this.processedMarkers = this.getAllMarkers()
      })
    },
    getAllMarkers() {
      return [
        ...this.markers,
        ...this.buildingMarkers,
        ...this.poiMarkers,
        ...this.labelMarkers,
        ...this.matchingMarkers,
        ...this.matchingPoiMarkers,
        ...this.selectMatchingMarkers,
        ...this.bimImageMarkers,
        ...this.emptyMarkers,
      ]
    },
    // 添加街道poi数据
    addPoiDatas(datas, typeCodes) {
      this.poiMarkers = []
      const points = []
      const markers = datas.map((item, index) => {
        const markerId = this.markerId++
        const data = {
          dataId: item.id, //业务数据ID
          ...item,
          id: markerId,
          iconType: item.typeCodes,
        }
        if (item.location) {
          const locations = item.location.split(',')
          data.longitude = parseFloat(locations[0])
          data.latitude = parseFloat(locations[1])
        } else if (item.longitude && item.latitude) {
          data.longitude = parseFloat(item.longitude)
          data.latitude = parseFloat(item.latitude)
        }
        if (data.longitude > 0 && data.latitude > 0) {
          points.push({
            longitude: data.longitude,
            latitude: data.latitude,
          })
        }

        return data
      })
      this.poiViewList = [...markers]
      this.$nextTick(() => {
        const markerList = markers.map(item => {
          return this.createMarker(item)
        })
        console.log(markerList)
        // mapCtx.addMarkers({
        //     markers: markerList
        // })
        this.poiMarkers = [...markerList]
        this.processedMarkers = this.getAllMarkers()
        // if(points.length > 1){
        //   this.includePoints = getBoundsBox(points)
        // }else if(points.length === 1){
        //   this.includePoints = getBoundsBox([...points,...points])
        // }
        this.setMarkersFitView(points)
        this.$nextTick(() => {
          this.poiViewList = []
        })
      })
    },
    // 添加街道建筑物数据
    addBuildingDatas(datas, industryTag) {
      this.buildingMarkers = []
      const points = []
      const markers = []
      datas.forEach((item, index) => {
        const data = {
          dataId: item.id, //业务数据ID
          idx: index + 1,
          ...item,
          id: this.markerId++,
        }
        if (item.longitude && item.latitude) {
          data.longitude = parseFloat(item.longitude)
          data.latitude = parseFloat(item.latitude)
        }
        if (data.longitude > 0 && data.latitude > 0) {
          points.push({
            longitude: data.longitude,
            latitude: data.latitude,
          })
          markers.push(data)
        }
      })
      this.buildingViewList = [...markers]
      this.$nextTick(() => {
        const markerList = markers.map(item => {
          return this.createMarker(item)
        })
        console.log(markerList)
        // mapCtx.addMarkers({
        //     markers: markerList
        // })
        this.buildingMarkers = [...markerList]
        this.processedMarkers = this.getAllMarkers()
        if (industryTag) {
          this.setMarkersFitView(points)
          // if(points.length > 1){
          //   this.includePoints = getBoundsBox(points)
          // }else if(points.length === 1){
          //   this.includePoints = getBoundsBox([...points,...points])
          // }
        }
      })
    },
    // 添加街道名称
    addLabels(name, center) {
      const labels = createLabel([
        { name, longitude: center.lng, latitude: center.lat },
      ])
      this.labelMarkers = labels
      this.processedMarkers = this.getAllMarkers()
      console.log(this.processedMarkers)
    },
    // 添加周边配置
    addMatchingDatas(datas) {
      this.matchingMarkers = []
      this.selectMatchingMarkers = []
      const markers = datas.map((item, index) => {
        const data = {
          ...item,
          dataId: item.matchingId, //业务数据ID
          markerId: parseInt(item.matchingId),
          iconType: item.matchingType,
          id: this.markerId++,
        }
        return data
      })
      this.matchingViewList = [...markers]
      this.$nextTick(() => {
        const markerList = markers.map(item => {
          return this.createIconMarker(item)
        })
        console.log(markerList)
        this.matchingMarkers = [...markerList]
        this.processedMarkers = this.getAllMarkers()
      })
    },
    addMatchingPoiDatas(datas, typeCodes) {
      this.matchingPoiMarkers = []
      this.selectMatchingMarkers = []
      const markers = datas.map((item, index) => {
        const data = {
          ...item,
          dataId: item.id, //业务数据ID
          markerId: parseInt(item.typeCodes) + index,
          iconType: item.typeCodes || typeCodes,
          id: this.markerId++,
        }
        if (item.location) {
          const locations = item.location.split(',')
          data.longitude = parseFloat(locations[0])
          data.latitude = parseFloat(locations[1])
        }
        return data
      })
      this.matchingPoiViewList = [...markers]
      this.$nextTick(() => {
        const markerList = markers.map(item => {
          return this.createIconMarker(item)
        })
        console.log(markerList)
        this.matchingPoiMarkers = [...markerList]
        this.processedMarkers = this.getAllMarkers()
      })
    },
    matchingPoiViewClickHandler(data) {
      const datas = [data]
      this.selectMatchingMarkers = []
      const markers = datas.map((item, index) => {
        const data = {
          ...item,
          dataId: item.matchingId, //业务数据ID
          markerId: parseInt(item.matchingId),
          iconType: item.iconType,
          id: this.markerId++,
        }
        return data
      })
      this.selectMatchingViewList = [...markers]
      this.$nextTick(() => {
        const markerList = markers.map(item => {
          return this.createMarker(item)
        })
        console.log(markerList)
        this.selectMatchingMarkers = [...markerList]
        this.processedMarkers = this.getAllMarkers()
      })
    },
    matchingViewImghandleClick() {
      this.selectMatchingMarkers = []
      this.processedMarkers = this.getAllMarkers()
    },
    addBimImage(data) {
      const datas = [data]
      this.bimImageMarkers = []
      this.bimImageViewList = []
      const markers = datas.map((item, index) => {
        const markerId = this.markerId++
        const data = {
          ...item,
          markerId: markerId,
          id: markerId,
          iconType: 1,
        }
        if (item.longitude && item.latitude) {
          data.longitude = parseFloat(item.longitude)
          data.latitude = parseFloat(item.latitude)
        }
        return data
      })
      this.bimImageViewList = [...markers]
      this.$nextTick(() => {
        const markerList = markers.map(item => {
          return this.createIconMarker(item)
        })
        console.log(markerList)
        this.bimImageMarkers = [...markerList]
        this.processedMarkers = this.getAllMarkers()
        this.$nextTick(() => {
          this.bimImageViewList = []
        })
      })
    },
    setCenter(data) {
      const mapRef = this.$refs.mapRef
      if (data.zoom) {
        mapRef._map.setZoomAndCenter(data.zoom, [data.longitude, data.latitude])
      } else {
        mapRef._map.setCenter([data.longitude, data.latitude])
      }
    },
    setPolygonsFitView(polygons, center) {
      const mapRef = this.$refs.mapRef
      if (mapRef._map) {
        let paths = []
        if (polygons && polygons.length) {
          const points = polygons[0].points || []
          paths = points.map(item => [item.longitude, item.latitude])
        }
        let polygon = new mapRef._maps.Polygon({
          path: paths,
          fillColor: '#ccebc5',
          strokeOpacity: 1,
          fillOpacity: 0.5,
          strokeColor: '#2b8cbe',
          strokeWeight: 1,
          strokeStyle: 'dashed',
          strokeDasharray: [5, 5],
        })
        mapRef._map.setFitView([polygon], true, [60, 60, 30, 30])
      } else {
        setTimeout(() => {
          this.setPolygonsFitView(polygons, center)
        }, 100)
      }
    },
    setMarkersFitView(points) {
      const mapRef = this.$refs.mapRef
      if (mapRef._map) {
        let markers = []
        if (points && points.length) {
          points.forEach(item => {
            markers.push(
              new mapRef._maps.Marker({
                position: new AMap.LngLat(item.longitude, item.latitude),
                icon: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                anchor: 'bottom-center',
              })
            )
          })
        }
        // mapRef._map.setFitView(markers,false,[60,60,80,80])
        mapRef._map.setFitView(markers, false, [200, 260, 30, 30], 15)
      } else {
        setTimeout(() => {
          this.setMarkersFitView(polygons)
        }, 100)
      }
    },
  },
}
</script>

<style lang="scss" scoped></style>
